<template>
  <div class="comment-item">
    <div class="comment-header">
      <div class="comment-author" v-if="comment.author">
        <el-avatar :src="comment.author.avatar_url" :size="32">
          {{ comment.author.username.charAt(0).toUpperCase() }}
        </el-avatar>
        <div class="author-info">
          <span class="author-name">{{ comment.author.username }}</span>
          <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
        </div>
      </div>
      <div class="comment-author" v-else>
        <el-avatar :size="32">匿名</el-avatar>
        <div class="author-info">
          <span class="author-name">匿名用户</span>
          <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
        </div>
      </div>
      
      <div class="comment-actions">
        <el-button size="small" text @click="$emit('reply', comment)">
          <el-icon><ChatDotRound /></el-icon>
          回复
        </el-button>
      </div>
    </div>
    
    <div class="comment-content">
      {{ comment.content }}
    </div>
    
    <!-- 回复列表 -->
    <div class="replies" v-if="comment.replies && comment.replies.length > 0">
      <CommentItem
        v-for="reply in comment.replies"
        :key="reply.id"
        :comment="reply"
        @reply="$emit('reply', $event)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Comment } from '@/types'

defineProps<{
  comment: Comment
}>()

defineEmits<{
  reply: [comment: Comment]
}>()

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}
</script>

<style scoped>
.comment-item {
  padding: 1rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #333;
  font-size: 0.875rem;
}

.comment-date {
  font-size: 0.75rem;
  color: #999;
}

.comment-actions {
  display: flex;
  gap: 0.5rem;
}

.comment-content {
  color: #333;
  line-height: 1.6;
  margin-bottom: 0.75rem;
}

.replies {
  margin-left: 2rem;
  padding-left: 1rem;
  border-left: 2px solid #f0f0f0;
}

@media (max-width: 768px) {
  .replies {
    margin-left: 1rem;
    padding-left: 0.5rem;
  }
}
</style>
